<?php
// +-------------------------------------------------------------------------------
// | DingZone [ A Rapid Development Framework For Dingtalk ]
// +-------------------------------------------------------------------------------
// | 微信js sdk拓展 v1.0
// |
// | Copyright (c) 2014-2018 http://www.heimalanshi.com All rights reserved.
// | Author : Jie
// | Date : 2018-08-09
// +-------------------------------------------------------------------------------

namespace wechat;

use think\Cache;
use think\Log;

/**
 * 微信js sdk类库扩展
 *
 * @author ZhuJie
 *
 */
class WeChatJSSDKExtension {
    private $appId;
    private $appSecret;

    public function __construct($appId, $appSecret) {
        $this->appId = $appId;
        $this->appSecret = $appSecret;
    }

    /**
     * 获取js签名
     *
     * @param $url
     * @return array
     */
    public function getSignPackage($url = false) {
        $jsapiTicket = $this->getJsApiTicket();
        if (!$jsapiTicket) {
            return false;
        }
        if (!$url) {
            $url = request()->url(true);
        }
        $timestamp = time();
        $nonceStr = $this->createNonceStr();

        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";

        $signature = sha1($string);

        $signPackage = array(
            "appId" => $this->appId,
            "nonceStr" => $nonceStr,
            "timestamp" => $timestamp,
            "url" => $url,
            "signature" => $signature,
            "rawString" => $string,
            "jsapiTicket" => $jsapiTicket
        );
        return $signPackage;
    }

    private function createNonceStr($length = 16) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    private function getJsApiTicket() {
        $key = "wechatjssdk.jsapiTicket." . $this->appId . "." . $this->appSecret;
        $data = Cache::get($key);
        if (!$data || $data['expire_time'] < time()) {
            $accessToken = $this->getAccessToken();
            if (!$accessToken) {
                return false;
            }
            $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
            $res = json_decode($this->httpGet($url), true);
            if (isset($res['ticket']) && $res['ticket']) {
                $data = [
                    'expire_time' => time() + 7000,
                    'jsapi_ticket' => $res['ticket']
                ];
                Cache::set($key, $data, 7000);
                return $res['ticket'];
            } else {
                Log::error("getJsApiTicket error. ret=" . json_encode($res));
                return false;
            }
        } else {
            return $data['jsapi_ticket'];
        }
    }

    private function getAccessToken() {
        $key = "wechatjssdk.accessToken." . $this->appId . "." . $this->appSecret;
        $data = Cache::get($key);
        if (!$data || $data['expire_time'] < time()) {
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret";
            $res = json_decode($this->httpGet($url), true);
            if (isset($res['access_token']) && $res['access_token']) {
                $data = [
                    'expire_time' => time() + 7000,
                    'access_token' => $res['access_token']
                ];
                Cache::set($key, $data, 7000);
                return $res['access_token'];
            } else {
                Log::error("getAccessToken error. ret=" . json_encode($res));
                return false;
            }
        } else {
            return $data['access_token'];
        }
    }

    private function httpGet($url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);

        $res = curl_exec($curl);
        curl_close($curl);

        return $res;
    }
}

?>